import React, {useState, useRef, useEffect} from 'react';
import Chat, {Bubble, Avatar} from '@chatui/core';
import ReactMarkdown from 'react-markdown';


export default function ChatMain({ sessionId }) {
    const [messages, setMessages] = useState([]);
    const memoryIdRef = useRef(sessionId);

    // 当sessionId变化时，重置聊天内容
    useEffect(() => {
        if (sessionId) {
            memoryIdRef.current = sessionId;
            setMessages([
                {
                    type: 'text',
                    content: {text: '你好，我是小云，有什么可以帮你？'},
                    position: 'left',
                    user: {
                        avatar: 'https://gw.alicdn.com/imgextra/i2/O1CN01fPEB9P1ylYWgaDuVR_!!6000000006619-0-tps-132-132.jpg',
                    },
                },
            ]);
        }
    }, [sessionId]);

    // 如果没有选中的会话，显示提示
    if (!sessionId) {
        return (
            <div style={{
                flex: 1,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                background: '#f8f9fa',
                color: '#6c757d',
                fontSize: 16
            }}>
                请选择或创建一个会话开始对话
            </div>
        );
    }

    // 渲染气泡内容，支持 markdown
    const renderMessageContent = (msg) => (
        <Bubble
            style={{
                borderRadius: 16,
                boxShadow: '0 2px 8px rgba(0,0,0,0.04)',
                background: msg.position === 'right' ? '#e6f7ff' : '#fff',
                color: '#222',
                fontSize: 16,
                maxWidth: '80%',
                padding: 0,
            }}
        >
            <div style={{padding: 12}}>
                <ReactMarkdown>{msg.content.text}</ReactMarkdown>
            </div>
        </Bubble>
    );


    // 发送消息
    const handleSend = async (type, val) => {
        if (type === 'text' && val.trim()) {
            const userMsg = {
                type: 'text',
                content: {text: val},
                position: 'right',
                user: {
                    avatar: 'https://gw.alicdn.com/imgextra/i2/O1CN01fPEB9P1ylYWgaDuVR_!!6000000006619-0-tps-132-132.jpg',
                }
            };
            setMessages((msgs) => [...msgs, userMsg]);
            // 获取当前的token
            const token = localStorage.getItem('token');
            const headers = {
                'Content-Type': 'application/json',
            };
            
            // 如果有token，添加Authorization头
            if (token) {
                headers['Authorization'] = `Bearer ${token}`;
            }
            
            const response = await fetch('/api/xiaoyun/chat', {
                method: 'POST',
                headers: headers,
                body: JSON.stringify({memoryId: memoryIdRef.current, message: val}),
            });

            if (!response.ok) {
                let errorMessage = '请求失败，请稍后重试。';
                
                if (response.status === 401 || response.status === 403) {
                    errorMessage = '登录已过期，请重新登录。';
                    // 清除本地存储，触发重新登录
                    localStorage.removeItem('token');
                    localStorage.removeItem('userInfo');
                    window.location.reload();
                    return;
                }
                
                setMessages((msgs) => [
                    ...msgs,
                    {
                        type: 'text',
                        content: {text: errorMessage},
                        position: 'left',
                        user: {
                            avatar: 'https://gw.alicdn.com/imgextra/i2/O1CN01fPEB9P1ylYWgaDuVR_!!6000000006619-0-tps-132-132.jpg',
                        }
                    },
                ]);
                return;
            }
            const botMsg = {
                type: 'text',
                content: {text: ''},
                position: 'left',
                user: {
                    avatar: 'https://gw.alicdn.com/imgextra/i2/O1CN01fPEB9P1ylYWgaDuVR_!!6000000006619-0-tps-132-132.jpg',
                }
            };
            setMessages((msgs) => [...msgs, botMsg]);

            const reader = response.body.getReader();
            const decoder = new TextDecoder('utf-8');
            let fullMessage = '';

            reader.read().then(function processText({done, value}) {
                if (done) {
                    console.log('Stream complete');
                    return;
                }
                const chunk = decoder.decode(value, {stream: true});
                fullMessage += chunk;

                // 逐步更新最后一条消息的内容
                setMessages((msgs) => {
                    const updatedMsgs = [...msgs];
                    const lastMsgIndex = updatedMsgs.length - 1;
                    if (updatedMsgs[lastMsgIndex].position === 'left') {
                        updatedMsgs[lastMsgIndex] = {
                            ...updatedMsgs[lastMsgIndex],

                            content: { text: fullMessage },
                        };
                    }
                    return updatedMsgs;
                });
                return reader.read().then(processText);
            });
        }
    };

    return (
        <div style={{flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0}}>
            <Chat
                navbar={{title: '小云智能助手'}}
                messages={messages}
                renderMessageContent={renderMessageContent}
                onSend={handleSend}
                placeholder="请输入你的问题"
                style={{flex: 1, minHeight: 0}}
            />
        </div>
    );
}
